package com.vipheyue.huaxue.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.google.gson.Gson;
import com.vipheyue.huaxue.R;
import com.vipheyue.huaxue.bean.AllCityBean;
import com.vipheyue.huaxue.cityList.Citym;
import com.vipheyue.huaxue.utils.FileService;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class CreateSchoolActivity extends AppCompatActivity {
    AllCityBean allCityBean=new AllCityBean();
    ArrayList<Citym> totalList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_school);
        allCityBean.setType("学校");
        try {
            bitchregister();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String bitchregister() throws Exception {
        File file=new File("/data/data/com.vipheyue.huaxue/files","test.txt");
        //创建一个读取流对象和文件相关联。
        FileReader fr = new FileReader(file);
        //为了提高效率。加入缓冲技术。将字符读取流对象作为参数传递给缓冲对象的构造函数。
        BufferedReader bufr = new BufferedReader(fr);
        String line = null;
        while((line=bufr.readLine())!=null)
        {
            System.out.print(line);
            Log.d("xxxdf",line)  ;
            register(line);
        }
        bufr.close();
        Collections.sort(totalList, comparator);
        allCityBean.setList(totalList);
      String totalGson=  new Gson().toJson(allCityBean);
        Log.d("CreateSchoolActivity", "  ");
        Log.d("CreateSchoolActivity", totalGson);
        Log.d("CreateSchoolActivity", "  ");
        FileService fileService = new FileService(this);
        fileService.save("school.txt", totalGson);
        return null;
    }

    private void register(String line) {
        Citym citym = new Citym();
        citym.setName(line);
        citym.setPinyi(PinyinHelper.convertToPinyinString(line, "", PinyinFormat.WITHOUT_TONE));
        totalList.add(citym);
    }

    /**
     * a-z排序
     */
    @SuppressWarnings("rawtypes")
    Comparator comparator = new Comparator<Citym>() {
        @Override
        public int compare(Citym lhs, Citym rhs) {
            String a = lhs.getPinyi().substring(0, 1);
            String b = rhs.getPinyi().substring(0, 1);
            int flag = a.compareTo(b);
            if (flag == 0) {
                return a.compareTo(b);
            } else {
                return flag;
            }
        }
    };
}
